#include "manager.h"

static char help[] = "pre-processor";

Manager::Manager(int argc, char **argv)
{
	if ( !addMethods() )
		throw Exception(__LINE__,__FILE__,"No methods were found.");

	if (argc != 3)
	{
		cout <<"\n#############################################################\n\n"
				"\tppUnified - Pre-processors Unified v1.0\n\n"
				"#############################################################\n";
		string msg;
		msg.append("You must type: ./exec mesh-file.msh method-name.\n");
		msg.append("For method-name, candidates are:");
		msg.append( candidatesMethods()+"\n\n" );
		throw Exception(__LINE__,__FILE__,msg.c_str());
		msg.clear();
	}

	ParUtil::Instance()->init(argc,argv);

#ifdef	_HAVE_PETSC_
	PetscInitialize(&argc,&argv,(char *)0,help);
#endif

	theMesh = MS_newMesh(0);			// initialize pointer
	M_load(theMesh, argv[1]);			// load mesh
	meshDim = theMesh->getDim();	// get mesh dimension: 2D/3D

	meshFilename = argv[1];
	method_name = argv[2];

	theMesh->modifyState(meshDim,1);	// create edge data structure
	theMesh->modifyState(0,meshDim);	// create adjacency around nodes
	if (meshDim == 2)
		theMesh->modifyState(1,2);			// create faces around edge

//	char filename[256];
//	sprintf(filename,"GeoCoef-%d-of-%d.msh",P_pid(),P_size());
//	AOMD_Util::Instance()->exportGmshFile(filename,theMesh);
}

Manager::~Manager()
{
	//setOfDomains.clear();
	methods.clear();
	ParUtil::Instance()->Finalize();
}

int Manager::addMethods()
{
	methods["pp-2D-old"] = calculateCoefficients2D_old;
	methods["pp-3D-old"] = calculateCoefficients3D_old;
	methods["pp-2D-new"] = calculateCoefficients2D_new;
	return methods.size();
}

void Manager::startPreProcessor()
{
	methodsIter = methods.find(method_name);
	pFuncMethod pfm;

	if ( methodsIter != methods.end() )
		pfm = methodsIter->second;
	else
	{
		char str[256];
		sprintf(str,"Unknown method %s\n",method_name.c_str());
		throw Exception(__LINE__,__FILE__,str);
	}
	pfm(theMesh,setOfDomains,meshFilename);
}

string Manager::candidatesMethods()
{
	string candidates;
	for (methodsIter=methods.begin(); methodsIter != methods.end(); methodsIter++)
	{
		candidates.append("\n");
		candidates.append(methodsIter->first);
	}
	return candidates;
}
